package edu.pku.sei.act.xmlTools;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Set;
import java.util.TreeSet;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import edu.pku.sei.act.taskStruct.TagNames;
import edu.pku.sei.act.taskStruct.Task;


public class XmlProcessor {
		
	public static Document readDocument(File inputXml)
	{
		SAXReader saxReader = new SAXReader();
		Document document = null;
        try {
			document = saxReader.read(inputXml);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();			
		}  
        return document;
	}
	
	public static Task genTaskStruct(Document document)
	{
		return new Task(document.getRootElement());
	}
	
	public static Document genDocument(Task task)
	{
		Document doc = DocumentHelper.createDocument();
		Element element = doc.addElement(TagNames.TASK);
		task.addAttrisAndEles(element);
		return doc;
	}
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String path = null;
		try {
			path = new File("").getCanonicalPath();
			path += "\\task.xml";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//System.out.println(path);		
		Document document = XmlProcessor.readDocument(new File(path));
		Task task = XmlProcessor.genTaskStruct(document);
		//System.out.println(XmlProcessor.genXml(task));		
		try {
			XMLWriter w = new XMLWriter(new OutputFormat("  ", true));
			w.write(XmlProcessor.genDocument(task));
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}				
	}

}
